package com.security.test.filter;

import com.alibaba.fastjson.JSON;
import com.security.test.config.MyUsernamePasswordAuthenticationToken;
import com.security.test.entity.LoginParameters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;

public class MyLoginFilter extends AbstractAuthenticationProcessingFilter {

    // 定义默认的RequestMatcher
    private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher("/user/login", "POST");


    public MyLoginFilter() {
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
    }

    // 自定义RequestMatcher的构造方法
    public MyLoginFilter(AntPathRequestMatcher matcher) {
        super(matcher);
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            System.out.println("MyLoginFilter");
            LoginParameters loginParameters = JSON.parseObject(request.getInputStream(), LoginParameters.class);
            return this.getAuthenticationManager()
                    .authenticate(new MyUsernamePasswordAuthenticationToken(loginParameters.getUsername(), loginParameters.getPassword()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
